var digitSegments = [
  [1, 2, 3, 4, 5, 6],
  [2, 3],
  [1, 2, 7, 5, 4],
  [1, 2, 7, 3, 4],
  [6, 7, 2, 3],
  [1, 6, 7, 3, 4],
  [1, 6, 5, 4, 3, 7],
  [1, 2, 3],
  [1, 2, 3, 4, 5, 6, 7],
  [1, 2, 7, 3, 6]
]

var timeClock = function () {
  var _years = document.querySelectorAll('.years');
  var _months = document.querySelectorAll('.months');
  var _dates = document.querySelectorAll('.dates');
  var _hours = document.querySelectorAll('.hours');
  var _minutes = document.querySelectorAll('.minutes');
  var _seconds = document.querySelectorAll('.seconds');

  setInterval(function () {
    var date = new Date();
    var years = date.getFullYear(),
      months = date.getMonth() + 1,
      dates = date.getDate(),
      hours = date.getHours(),
      minutes = date.getMinutes(),
      seconds = date.getSeconds();

    setNumber(_years[0], Math.floor((years % 10000) / 1000), 1);
    setNumber(_years[1], Math.floor((years % 1000) / 100), 1);
    setNumber(_years[2], Math.floor((years % 100) / 10), 1);
    setNumber(_years[3], years % 10, 1);

    setNumber(_months[0], Math.floor(months / 10), 1);
    setNumber(_months[1], months % 10, 1);

    setNumber(_dates[0], Math.floor(dates / 10), 1);
    setNumber(_dates[1], dates % 10, 1);

    setNumber(_hours[0], Math.floor(hours / 10), 1);
    setNumber(_hours[1], hours % 10, 1);

    setNumber(_minutes[0], Math.floor(minutes / 10), 1);
    setNumber(_minutes[1], minutes % 10, 1);

    setNumber(_seconds[0], Math.floor(seconds / 10), 1);
    setNumber(_seconds[1], seconds % 10, 1);
  }, 1000);
}

var setNumber = function (digit, number) {
  var segments = digit.querySelectorAll('.segment');
  var current = parseInt(digit.getAttribute('data-value'));

  // only switch if number has changed or wasn't set
  if (!isNaN(current) && current != number) {
    // unset previous number
    digitSegments[current].forEach(function (digitSegment, index) {
      setTimeout(function () {
        segments[digitSegment - 1].classList.remove('on');
      }, index * 45)
    });
  }

  if (isNaN(current) || current != number) {
    // set new number after
    setTimeout(function () {
      digitSegments[number].forEach(function (digitSegment, index) {
        setTimeout(function () {
          segments[digitSegment - 1].classList.add('on');
        }, index * 45)
      });
    }, 250);
    digit.setAttribute('data-value', number);
  }
}

export default timeClock
